package ru.arriah.servicedesk.web.dispatcher.action;

import java.io.IOException;
import java.util.Collection;
import java.util.Date;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.bean.ClientBean;
import ru.arriah.servicedesk.bean.DepartmentBean;
import ru.arriah.servicedesk.bean.GroupBean;
import ru.arriah.servicedesk.bean.OrganizationBean;
import ru.arriah.servicedesk.bean.RequestBean;
import ru.arriah.servicedesk.bean.RequestStatusBean;
import ru.arriah.servicedesk.bean.RequestTypeBean;
import ru.arriah.servicedesk.bean.error.RequestFormErrorBean;
import ru.arriah.servicedesk.ejb.ClientManagerLocalHome;
import ru.arriah.servicedesk.ejb.ClientManagerLocalObject;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalHome;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalObject;
import ru.arriah.servicedesk.ejb.GroupManagerLocalHome;
import ru.arriah.servicedesk.ejb.GroupManagerLocalObject;
import ru.arriah.servicedesk.ejb.OrganizationManagerLocalHome;
import ru.arriah.servicedesk.ejb.OrganizationManagerLocalObject;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.InternalException;


public class CommitRequestAction extends DumbAction {
  protected RequestFormErrorBean requestFormErrorBean;  
  protected RequestManagerLocalHome requestManagerHome;
  protected EmployeeManagerLocalHome employeeManagerHome;
  protected OrganizationManagerLocalHome organizationManagerHome;
  protected ClientManagerLocalHome clientManagerHome;
  protected GroupManagerLocalHome groupManagerHome;

  public CommitRequestAction() throws NamingException {
    super();

    requestManagerHome = 
      Utils.getRequestManagerHomeInterface();
    organizationManagerHome = 
      Utils.getOrganizationManagerHomeInterface();
    clientManagerHome = 
      Utils.getClientManagerHomeInterface();
    groupManagerHome = 
      Utils.getGroupManagerHomeInterface();
    employeeManagerHome = 
      Utils.getEmployeeManagerHomeInterface();    
  }

  
  /**
   * Validate request
   * @param requestBean
   * @return
   */
  private boolean isValid(RequestBean requestBean, RequestManagerLocalObject requestManager) {
    requestFormErrorBean = new RequestFormErrorBean();
    boolean result = true;

    if (requestBean.getOrganizationId() == 0) {
      requestFormErrorBean.setOrganization(
        config.getProperty("ERROR.REQUESTFORM.ORGANIZATION")
      );
      result = false;
    }

    if (requestBean.getDepartmentId() == 0) {
      requestFormErrorBean.setDepartment(
        config.getProperty("ERROR.REQUESTFORM.DEPARTMENT")
      );
      result = false;
    }

    if (requestBean.getClientId() == 0) {
      requestFormErrorBean.setClient(
        config.getProperty("ERROR.REQUESTFORM.CLIENT")
      );
      result = false;
    }

    if (requestBean.getDispatcherText() == null || requestBean.getDispatcherText().equals("")) {
      requestFormErrorBean.setDispatcherText(
        config.getProperty("ERROR.REQUESTFORM.DISPATCHERTEXT")
      );
      result = false;
    }

    if (requestBean.getClientText() == null || requestBean.getClientText().equals("")) {
      requestFormErrorBean.setClientText(
        config.getProperty("ERROR.REQUESTFORM.CLIENTTEXT")
      );
      result = false;
    }

    if (requestBean.getGroupId() == 0) {
      requestFormErrorBean.setGroup(
        config.getProperty("ERROR.REQUESTFORM.GROUP")
      );
      result = false;
    }

    if (requestBean.getRequestTypeId() == 0) {
      requestFormErrorBean.setRequestType(
        config.getProperty("ERROR.REQUESTFORM.REQUESTTYPE")
      );
      result = false;
    }
    
    /* is request status = new (1) ? */
    RequestStatusBean originalRequestStatus = 
      requestManager.selectRequestStatus(requestBean.getId());
    if (originalRequestStatus!=null) {
      if (originalRequestStatus.getId() != 1) {
        result = false;
      }    
    } else result = false;
    
    return result;
  }

  public String execute(ActionMapping actionMapping,
    HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
    try {
      RequestManagerLocalObject requestManager = 
        requestManagerHome.create();
      EmployeeManagerLocalObject employeeManager = 
        employeeManagerHome.create();

      int userId = Utils.getUserId(request);

      RequestBean requestBean = new RequestBean();
      int requestId = idVal(request.getParameter("id"));
      if (requestId == 0)
        throw new Exception("invalid id");

      requestBean.setId(requestId);
      requestBean.setClientText(request.getParameter("text"));
      requestBean.setDispatcherText(request.getParameter("dispatcherText"));

      requestBean.setOrganizationId(idVal(request.getParameter("organization_id")));
      requestBean.setDepartmentId(idVal(request.getParameter("department_id")));
      requestBean.setClientId(idVal(request.getParameter("client_id")));

      requestBean.setGroupId(idVal(request.getParameter("group_id")));
      requestBean.setRequestTypeId(idVal(request.getParameter("requesttype_id")));
      requestBean.setRegistrationDate(new Date());
      requestBean.setRegNumber(request.getParameter("regNumber"));
      requestBean.setRoom(request.getParameter("room"));
      requestBean.setComment(
        request.getParameter("comment")
      );

      requestBean.setStatusId(3);
      requestBean.setPriority(3);

      int leadExecutorId = 
        employeeManager.selectLeadExecutorId(requestBean.getGroupId());
      requestBean.setLeadExecutorId(leadExecutorId);

      
      /* Request not valid */
      if (!this.isValid(requestBean, requestManager)) {
        OrganizationManagerLocalObject organizationManager = 
          organizationManagerHome.create();
        ClientManagerLocalObject clientManager = clientManagerHome.create();
        GroupManagerLocalObject groupManager = groupManagerHome.create();

        //TODO replace static id to real id
        Collection<DepartmentBean> departmentsList = 
          organizationManager.selectDepartments(1);

        Collection<OrganizationBean> organizationsList = 
          organizationManager.selectOrganizations();

        Collection<ClientBean> clientsList = 
          clientManager.selectClients();

        Collection<RequestTypeBean> requestTypesList = 
          requestManager.selectRequestTypes();

        Collection<GroupBean> groupsList = groupManager.selectGroups();

        organizationManager.remove();
        clientManager.remove();
        requestManager.remove();
        groupManager.remove();
        employeeManager.remove();

        request.setAttribute("groupsList", groupsList);
        request.setAttribute("requestTypesList", requestTypesList);
        request.setAttribute("organizationsList", organizationsList);
        request.setAttribute("clientsList", clientsList);
        request.setAttribute("departmentsList", departmentsList);
        request.setAttribute("requestBean", requestBean);
        request.setAttribute("error", requestFormErrorBean);
        
        addErrorMessage(request, config.getProperty("ERROR.REQUESTFORM_FIELDS_INVALID"));        
        return actionMapping.getFailureTarget();
      }
      
      // Request is valid
      if (requestManager.updateRequest(requestBean, userId))
        addInfMessage(request, config.getProperty("INF.REQUEST_COMMITTED"));
      else
        addErrorMessage(request, config.getProperty("ERROR.REQUEST_NOT_COMMITTED"));

      employeeManager.remove();
      requestManager.remove();
      
      
      //Display requests list
      ListRequestsAction listRequestsAction = 
        new ListRequestsAction(requestManagerHome);
      listRequestsAction.setConfig(config);
      
      return listRequestsAction.execute(actionMapping, request, response);
    } catch (Exception e) {
      handleException(e, "execute");
      throw new InternalException("ErrorMessage.internal");
    }
  }
}